﻿using Basic.FlowModel.DB;
using Basic.FlowRemoteModel.FlowAppMsg.Model;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Basic.FlowDAL.lmpl
{
    internal class FlowAppMsgTemplateDAL : BasicDAL<DBFlowAppMsgTemplate, long>, IFlowAppMsgTemplateDAL
    {
        public FlowAppMsgTemplateDAL ( IRepository<DBFlowAppMsgTemplate> basicDAL ) : base(basicDAL, "app.msg.template")
        {
        }

        public void Adds ( long appId, long formId, FlowAppMsgAdd[] adds )
        {
            DBFlowAppMsgTemplate[] datas = adds.ConvertAll(( a, i ) => new DBFlowAppMsgTemplate
            {
                AppId = appId,
                FormId = formId,
                IsRow = a.IsRow,
                Keywords = a.Keywords,
                DataType = a.DataType,
                ColId = a.ColId,
                Id = IdentityHelper.CreateId(),
                IsRed = a.IsRed,
                Show = a.Show,
                Label = a.Label,
                Sort = (short)( i + 1 ),
                Value = a.Value
            });
            this._BasicDAL.Insert(datas);
        }
        public void Clear ( long appId, long formId )
        {
            if ( !this._BasicDAL.Delete(a => a.AppId == appId && a.FormId == formId) )
            {
                throw new ErrorException("flow.app.msg.delete.fail");
            }
        }
        public void Sets ( long appId, long formId, FlowAppMsgAdd[] adds )
        {
            if ( adds.IsNull() )
            {
                this.Clear(appId, formId);
                return;
            }
            DBFlowAppMsgTemplate[] datas = adds.ConvertAll(( a, i ) => new DBFlowAppMsgTemplate
            {
                AppId = appId,
                DataType = a.DataType,
                ColId = a.ColId,
                Id = IdentityHelper.CreateId(),
                IsRed = a.IsRed,
                Label = a.Label,
                Keywords = a.Keywords,
                IsRow = a.IsRow,
                Show = a.Show,
                Sort = (short)( i + 1 ),
                FormId = formId,
                Value = a.Value
            });
            ISqlQueue<DBFlowAppMsgTemplate> queue = this._BasicDAL.BeginQueue();
            queue.Delete(a => a.AppId == appId && a.FormId == formId);
            queue.Insert(datas);
            _ = queue.Submit();
        }
    }
}
